package com.rk.section1;

import java.text.DecimalFormat;
import java.util.Map;

/**
 * 重构书籍中的第一个例子：戏剧演出团打印账单详情
 */
public class Statement {

    public String statement(Invoice invoice, Map<String, Play> plays) {
        return renderText(new StatementDataCreator().createStatementData(invoice, plays));
    }

    private String renderText(StatementData data) {
        StringBuilder result = new StringBuilder();
        result.append(String.format("Statement for %s\n", data.getCustomer()));
        for (Performance performance : data.getPerformances()) {
            result.append(String.format("  %s:%s (%d seats)\n", performance.getPlay().getName(), usd(performance.getAmount()), performance.getAudience()));
        }
        result.append(String.format("Amout owed is %s\n", usd(data.getTotalAmount())));
        result.append(String.format("You earned %scredits\n", data.getTotalVolumeCredits()));
        return result.toString();
    }

    public String statementHtml(Invoice invoice, Map<String, Play> plays) {
        return renderHtml(new StatementDataCreator().createStatementData(invoice, plays));
    }

    private String renderHtml(StatementData data) {
        StringBuilder result = new StringBuilder();
        result.append(String.format("<h1>Statement for %s</h1>\n", data.getCustomer()));
        result.append("<table>\n");
        result.append("  <tr><th>play</th><th>seats</th><th>cost</th></tr>\n");
        for (Performance performance : data.getPerformances()) {
            result.append(String.format("  <tr><td>%s</td><td>%s</td><td>%d</td></tr>\n", performance.getPlay().getName(), usd(performance.getAmount()), performance.getAudience()));
        }
        result.append("</table>\n");
        result.append(String.format("<p>Amout owed is <em>%s</em></p>\n", usd(data.getTotalAmount())));
        result.append(String.format("<p>You earned <em>%s</em>credits</p>\n", data.getTotalVolumeCredits()));
        return result.toString();
    }

    private String usd(int totalAmount) {
        return new DecimalFormat("$,###.00").format(totalAmount / 100);
    }


}
